<template>
<div>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-row :gutter="20">
            <el-col :span="8">
                <el-input v-model="query.query" clearable @clear="getUserList">
                    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input>
            </el-col>
            <el-col :span="16">
                <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
            </el-col>
        </el-row>
        <el-table :data="userlist" stripe border>
            <el-table-column type="index" label="#" />
            <el-table-column prop="username" label="姓名" width="120px" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="mobile" label="电话" />
            <el-table-column prop="role_name" label="角色" />
            <el-table-column prop="mg_state" label="状态">
                <!-- scope随便写的，是一个对象 -->
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.mg_state" @change="userStateFn(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUserFn(scope.row.id)"></el-button>
                    <el-tooltip content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRoleDialogFn(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.pagenum" :page-sizes="[1,2,3]" :page-size="query.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </el-card>
    <!-- 放在根标签结尾的前面 -->
    <!-- 添加对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddFormFn">
        <el-form ref="addFormRef" label-width="80px" :model="addForm" :rules="addFormRules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveAddFormFn">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog v-if="editDialogVisible" title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
        <el-form ref="editFormRef" label-width="80px" :model="editForm" :rules="addFormRules">
            <el-form-item label="用户名">
                <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveEditFormFn">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%">
        <p>用户名：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <div>
          <!-- v-model="value"选中了哪个就是哪个 -->
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="roleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRoleFn">确 定</el-button>
        </span>
    </el-dialog>

</div>
</template>

<script>
// 遇到错误怎么办？
// 1. 习惯：控制台打开 普通错误看控制台
// 2. 百度 google(翻墙软件)
// 3. 凡是涉及到ajax的还要看一个地方 network 请求头和请求体

// 作用域插槽

// get  delete axios.get(url,{params:{}})
// post put axios.post(url,{}) 固定写法
// 接口中的数据一般要存到data中，因为data是响应式的，可以和视图一一对应 mvvm

export default {
  data () {
    // callback()校验通过
    // callback(new Error('错误信息')) 校验失败
    // rule 规则
    // value 要校验的数据
    // callback
    const checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式不对'))
      }
      callback() // 校验通过
    }

    const checkMobile = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return callback(new Error('手机格式不对'))
      }
      callback() // 校验通过
    }
    return {
      query: {
        query: '', // 查询关键字
        pagenum: 1, // 当前页码
        pagesize: 10 // 每页数据条数
      },
      userlist: [],
      total: 0,
      addDialogVisible: false, // 默认隐藏
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '长度在3到10之间',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '邮箱不能为空',
          trigger: 'blur'
        }, {
          validator: checkEmail,
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          message: '手机号不能为空',
          trigger: 'blur'
        }, {
          validator: checkMobile,
          trigger: 'blur'
        }]
      },
      editDialogVisible: false,
      editForm: {},
      roleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: null
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async setRoleFn () {
      if (!this.selectedRoleId) return this.$message.error('请选择新的角色')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.roleDialogVisible = false
      this.getUserList()// 重新获取列表数据
      this.selectedRoleId = null // 重置选中的角色id
    },
    async getUserList () {
      const {
        data: res
      } = await this.$http.get('users', {
        params: this.query
      })
      // console.log(res)
      this.userlist = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (size) {
      console.log(size)
      this.query.pagesize = size
      this.getUserList()
    },
    handleCurrentChange (page) {
      console.log(page)
      this.query.pagenum = page
      this.getUserList()
    },
    async userStateFn (row) {
      console.log(row)
      // 同步到数据库 接口
      const {
        data: res
      } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        row.mg_state = !row.mg_state
      }
      this.$message.success(res.meta.msg)
    },
    resetAddFormFn () {
      this.$refs.addFormRef.resetFields()
    },
    saveAddFormFn () {
      // 预校验 写之前找类似的代码参考一下
      // valid validate
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return console.log('校验失败') // 中止 不往后执行
        // get ,delete (url,{params:{参数}})
        // post put (url,参数)
        const {
          data: res
        } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false // 关闭对话框
        // 如果创建成功了，说明页面中的表格中的数据变旧了
        this.getUserList() // 重新获取最新的数据
      })
    },
    async showEditDialog (id) {
      this.editDialogVisible = true
      const {
        data: res
      } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询当前用户失败')
      console.log(res)
      this.editForm = res.data
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    saveEditFormFn () {
      // 预校验
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return console.log('校验失败')
        const {
          data: res
        } = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        // 重新获取一次数据
        this.getUserList()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    delUserFn (id) {
      // promise和async,await本质没有区别，只不过换一个写法
      // then成功 catch失败
      console.log(id)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {
          data: res
        } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async showRoleDialogFn (row) {
      this.roleDialogVisible = true
      console.log(row)
      this.userInfo = row
      // 报错怎么解决
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败')
      console.log(res)
      this.rolesList = res.data
    }
  },
  computed: {

  }
}
</script>

<style scoped>

</style>
